package com.ant.business.system.controller;

import com.alibaba.fastjson.JSON;
import com.ant.business.system.entity.Module;
import com.ant.business.system.entity.RoleModule;
import com.ant.business.system.entity.User;
import com.ant.business.system.service.*;
import com.ant.common.annotation.AuthIgnore;
import com.ant.common.result.ResponseResult;
import com.ant.common.utils.FastMap;
import com.ant.common.utils.IdWorker;
import com.ant.common.utils.IntegerUtil;
import com.ant.common.utils.StringUtil;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户管理控制层
 *
 * @author
 * @description
 * @create 2021-03-22 14:25:56
 */
@RestController
@RequestMapping(value = "/user")
@Slf4j
@Api(tags = "用户管理")
public class UserController {

    private final UserService userService;

    private final UserRoleService userRoleService;

    private final RoleService roleService;

    private final ModuleService moduleService;

    private final UserTokenService userTokenService;

    public UserController(UserService userService, UserRoleService userRoleService, RoleService roleService, UserTokenService userTokenService,
                          ModuleService moduleService) {
        this.userService = userService;
        this.userRoleService = userRoleService;
        this.roleService = roleService;
        this.userTokenService = userTokenService;
        this.moduleService = moduleService;
    }

    @PostMapping(value = "/login", name = "用户登录")
    @ApiOperation("用户登录")
    @AuthIgnore
    public ResponseResult login(@RequestBody FastMap param) {
        try {
            String userName = param.getString("userName");
            String password = param.getString("password");

            if (StringUtil.isEmpty(userName)) {
                return ResponseResult.fail("用户名不能为空");
            }

            if (StringUtil.isEmpty(password)) {
                return ResponseResult.fail("密码不能为空");
            }

            List<User> userList = userService.getUserByMobile(userName, password);
            if (userList.size() > 0) {
                String token = IdWorker.getIdByNum(128);
                User user = userList.get(0);
                user.setPassword("");
                user.setToken(token);
                String userJson = JSON.toJSONString(user);
                log.info("登录成功：" + userJson);

                userTokenService.saveToken(user, token);
                return ResponseResult.success(user);
            } else {
                log.info("登录失败，用户名密码不正确");
                return ResponseResult.fail("登录失败，用户名密码不正确");
            }
        } catch (Exception e) {
            log.info("登录失败：" + e.getMessage());
            return ResponseResult.fail("登录失败：" + e.getMessage());
        }
    }

    @PostMapping(value = "/logout")
    public ResponseResult logout(HttpServletRequest request) {
        try {
            String token = request.getHeader("token");
            userTokenService.deleteToken(token);
            return ResponseResult.success("success");
        } catch (Exception e) {
            return ResponseResult.fail("fail");
        }
    }

    /**
     * 用户管理分页查询列表
     *
     * @return
     */
    @PostMapping(value = "/list", name = "用户管理分页查询列表")
    @ApiOperation("用户管理分页查询列表")
    public ResponseResult list(@RequestBody FastMap param) {
        try {
            PageInfo<User> pages = userService.getList(param.getInt("page"), param.getInt("limit"), param);
            log.info("用户管理分页查询列表成功");
            return ResponseResult.success("用户管理分页查询列表成功", pages.getList(), pages.getTotal());
        } catch (Exception e) {
            log.info("用户管理分页查询列表失败：" + e.getMessage());
            return ResponseResult.fail("用户管理分页查询列表失败：" + e.getMessage());
        }
    }

    /**
     * 修改用户管理（新增、修改）
     *
     * @param user
     * @return
     */
    @PostMapping(value = "/edit", name = "修改用户管理")
    @ApiOperation("修改用户管理（新增、修改）")
    public ResponseResult edit(@RequestBody User user) {
        try {
            if (Objects.isNull(user.getUserId()) || user.getUserId() <= 0) {
                //新增
                userService.saveOne(user);
                log.info("用户管理新增成功");
            } else {
                //编辑
                userService.update(user);
                log.info("用户管理修改成功");
            }
            return ResponseResult.success("用户管理编辑成功");
        } catch (Exception e) {
            log.info("用户管理编辑失败：" + e.getMessage());
            return ResponseResult.fail("用户管理编辑失败：" + e.getMessage());
        }
    }

    /**
     * 删除用户
     *
     * @param primaryKey
     * @return
     */
    @PostMapping(value = "/delete", name = "删除用户")
    @ApiOperation("删除用户")
    public ResponseResult delete(String primaryKey) {
        try {
            if (Objects.isNull(primaryKey) || primaryKey.length() == 0) {
                return ResponseResult.fail("没有找到用户编号");
            }
            userService.delete(primaryKey);
            log.info("用户删除成功");
            return ResponseResult.success("用户删除成功");
        } catch (Exception e) {
            log.info("用户删除失败：" + e.getMessage());
            return ResponseResult.fail("用户删除失败：" + e.getMessage());
        }
    }

    /**
     * 通过角色查询用户列表
     *
     * @return
     */
    @PostMapping(value = "/roleUserList", name = "通过角色查询用户列表")
    @ApiOperation("通过角色查询用户列表")
    public ResponseResult roleUserList(@RequestBody FastMap param) {
        try {
            int roleId = param.getInt("roleId");
            if (roleId == 0) {
                return ResponseResult.fail("角色编号不能为空");
            }

            List<Integer> userIdList = new ArrayList<>();
            if (IntegerUtil.isNotEmpty(roleId)) {
                List<User> userRoleList = userService.getUserByRoleId(roleId);
                userIdList = userRoleList.stream().map(User::getUserId).collect(Collectors.toList());
            }

            List<FastMap> userList = userService.getAllList(param).stream().map(x -> {
                FastMap userMap = new FastMap();
                userMap.put("userId", x.getUserId());
                userMap.put("userName", x.getUserName());
                return userMap;
            }).collect(Collectors.toList());

            List<Integer> finalUserIdList = userIdList;
            List<String> userNameList = userList.stream().map(x -> x.getString("userName")).collect(Collectors.toList());
            List<String> checkRoleUserList = userList.stream().filter(x -> finalUserIdList.contains(x.getInt("userId"))).collect(Collectors.toList())
                    .stream().map(x -> x.getString("userName")).collect(Collectors.toList());

            FastMap resultMap = new FastMap();
            resultMap.put("userList", userList);
            resultMap.put("userNameList", userNameList);
            resultMap.put("checkRoleUserList", checkRoleUserList);

            log.info("用户列表查询成功");
            return ResponseResult.success("用户列表查询成功", resultMap);
        } catch (Exception e) {
            log.info("用户列表查询失败：", e);
            return ResponseResult.fail("用户列表查询失败：" + e.getMessage());
        }
    }


    /**
     * 更新用户角色
     *
     * @param param
     * @return
     */
    @PostMapping(value = "/updateUserRole")
    @ApiOperation("更新用户角色")
    public ResponseResult updateUserRole(@RequestBody FastMap param) {
        try {
            userRoleService.updateUserRole(param);
            log.info("更新用户角色成功");
            return ResponseResult.success("更新用户角色成功");
        } catch (Exception e) {
            log.info("更新用户角色失败：" + e.getMessage());
            return ResponseResult.fail("更新用户角色失败：" + e.getMessage());
        }
    }

    /**
     * 获取模块信息
     *
     * @return
     */
    @PostMapping(value = "/getModuleInfo")
    @ApiOperation("获取模块信息")
    public ResponseResult getModuleInfo() {
        try {
            List<FastMap> list = userService.getModuleInfo();
            return ResponseResult.success(list);
        } catch (Exception e) {
            log.info("获取模块信息失败：" + e.getMessage());
            return ResponseResult.fail("获取模块信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取角色模块信息
     *
     * @param param
     * @return
     */
    @PostMapping(value = "/roleModuleList")
    @ApiOperation("获取角色模块信息")
    public ResponseResult roleModuleList(@RequestBody FastMap param) {
        try {
            List<Integer> checkedModuleList = roleService.getRoleModuleList(param).stream().map(Module::getId).collect(Collectors.toList());
            List<Module> allModule = moduleService.getAllModule();
            Map<String, List<Module>> groupMap = allModule.stream().collect(Collectors.groupingBy(Module::getModuleGroupName));

            List<FastMap> moduleList = new ArrayList<>();
            int index = -1;
            for (Map.Entry<String, List<Module>> groupEntry : groupMap.entrySet()) {
                String groupName = groupEntry.getKey();
                FastMap groupModuleMap = new FastMap();
                groupModuleMap.put("moduleId", index);
                groupModuleMap.put("moduleName", groupName);

                List<Module> value = groupEntry.getValue();
                List<FastMap> children = new ArrayList<>();
                for (Module module : value) {
                    FastMap child = new FastMap();
                    child.put("moduleId", module.getId());
                    child.put("moduleName", module.getName());
                    children.add(child);
                }
                groupModuleMap.put("children", children);
                moduleList.add(groupModuleMap);
                index--;
            }

            FastMap resultMap = new FastMap();
            resultMap.put("moduleList", moduleList);
            resultMap.put("checkedModuleList", checkedModuleList);

            return ResponseResult.success(resultMap);
        } catch (Exception e) {
            log.info("获取角色模块信息失败：", e);
            return ResponseResult.fail("获取角色模块信息失败：" + e.getMessage());
        }
    }
}